<?php

/**
 * 退换货行为类
 * @copyright   Copyright (c) 2006 - 2010 DZH 友拓软件友拓通
 * @category    销售
 * @package   Behavior
 * @author     庄敏学
 * @version  2.1,2012-07-22
 */

class ReturnSaleOrderPublicBehavior extends Behavior {
	
	public function run(&$params){
		//添加换货销售
		if($params['return_sale_order_type']==2&&!empty($params['sale'])){
			$sale_data	= $this->saleData($params);
			$sale_data['module_name'] = 'SaleOrder';
			$id			= $params['id'];
			//添加换货销售单
			$_POST		= $sale_data;
			$sale	    = D('SaleOrder');
			$sale->setModuleInfo('SaleOrder','insert');
			$sale->relationInsert();// 指定模块名称
			$sale_id	= $sale->id;
			//退货单中补充销售单信息
			$info		= M('SaleOrder')->find($sale_id);
			$data		= array('sale_order_id'=>$sale_id,'sale_order_no'=>$info['sale_order_no']);
	 		M('ReturnSaleOrder')->where('id='.$id)->setField($data);
	 		$_POST		= $params; 
	 		$params['id']=$id;
		}
		if(ACTION_NAME=='delete'){
			$this->deleteSaleData($params['id']);
		}
	}
	
	///换货生成销售数据
	public function saleData($info){
		$sale_data['detail'] 				= $info['sale'];
		$sale_data['client_id']				= $info['client_id'];
		$sale_data['basic_id']				= $info['basic_id'];
		$sale_data['currency_id']			= $info['currency_id'];
		$sale_data['order_date']			= $info['return_order_date'];
		$sale_data['expect_shipping_date']	= $info['return_order_date'];
		$sale_data['comments']				= $info['comments'];
		$sale_data['audit_state']			= 1;
		$sale_data['order_type']			= 2;
		$sale_data['submit_type']			= $info['submit_type'];
		return $sale_data;
	}
	
	 /// 删除退换货时 删除换货
	public function deleteSaleData($id){
		$var	= M('return_sale_order_del')->find(intval($id));
		//换货需删除销售单
		if($var['return_sale_order_type']==2){
			$model	= D('SaleOrder');
			$model->setModuleInfo('SaleOrder','delete');
			$model->relationDelete(intval($var['sale_order_id']),'saleOrder');
		}
	}
	
	/// 退换货删除验证
	protected  function delete(&$params){
		$id	 = intval($params['id']);
		$var = M('return_sale_order')->field('sale_order.id as id,return_sale_order_no,return_sale_order_type,sale_order_state,return_sale_order.invoice_state')->join('left join sale_order on return_sale_order.sale_order_id=sale_order.id')->where('return_sale_order.id='.$id)->find();
		if($var['invoice_state']==2){
			throw_json(L('been_invoiced'));
		}
		$params = $var;
		$params['module_name']	= 'SaleOrder';
		if($params['return_sale_order_type']==2){
			tag('SaleOrder&delete',&$params);
		}
	}
}